#! /usr/bin/env python
#coding:utf-8
import urllib2,cookielib,socket
from gzipHandle import ContentEncodingProcessor
class Browser(object):
    def __init__(self,headers=None,middleware=None):
        socket.setdefaulttimeout(60) #60秒超时
        self.middleware = middleware
        self.headers ={'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36'}
        if isinstance(headers,dict):
            self.headers =dict(self.headers, **headers)
        #http 代理支持
        #proxy_support = urllib2.ProxyHandler({'http':'http://XX.XX.XX.XX:XXXX'})
        #cookie 支持
        self.cookieHandle = cookielib.CookieJar()
        #gzip支持
        gzipHandle = ContentEncodingProcessor
        opener = urllib2.build_opener(gzipHandle,urllib2.HTTPCookieProcessor(self.cookieHandle))
        urllib2.install_opener(opener)
    def request(self,url):
        req = urllib2.Request(url,headers=self.headers)
        resp = urllib2.urlopen(req,timeout=15)
        resp.content  = resp.read()
        if self.middleware:
            # handle 为中间件入口函数
            ret = self.middleware.handle(resp)
            if ret:
                resp = ret
        content_type =resp.info().getheader("Content-Type")
        content_type = content_type.lower()
        if content_type and content_type.find('text/') != -1:
            # TODO 编码判断不严格
            if content_type.find('gb')!=-1:
                try:
                    resp.content = resp.content.decode('GBK')
                except Exception,e:
                    print 'Decode error'+e
        return resp
if __name__=='__main__':
    b = Browser()
    print b.request('http://www.baidu.com/')

